<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    :width="props.templateId ? '950px' : '560px'"
    :before-close="handleClose"
    class="create-project-form-dialog"
    :lock-scroll="true"
    :modal="true"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="dialog-content-wrapper">
      <div class="dialog-content" :align-center="false" v-loading="loading">
        <!-- 左侧：模板预览 - 只在模板创建时显示 -->
        <div class="left-preview" v-if="props.templateId">
          <div class="preview-image">
            <img
              :src="
                projectCover ||
                templateDetail?.cover ||
                '/api/placeholder/280/160'
              "
              :alt="getTemplateName()"
            />
          </div>
          <div class="template-info">
            <h4 class="template-name">{{ getTemplateName() }}</h4>
            <p class="template-description">
              {{ templateDetail?.remark || "模板项目的描述信息" }}
            </p>
          </div>
          <div class="change-cover-section">
            <div class="section-label">项目封面</div>
            <div class="template-cover-info">
              <span class="cover-source-text">使用模板封面</span>
            </div>
            <el-upload
              ref="uploadRef"
              class="cover-upload"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              action="#"
              accept="image/*"
            >
              <el-button class="change-cover-btn">
                <el-icon style="margin-right: 6px">
                  <Upload />
                </el-icon>
                更改封面
              </el-button>
            </el-upload>
          </div>
        </div>

        <!-- 右侧：表单 -->
        <div class="right-form" :class="{ 'full-width': !props.templateId }">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            label-width="100px"
            :label-position="!props.templateId ? 'top' : 'top'"
          >
            <!-- 项目名称 -->
            <el-form-item label="项目名称" prop="name" required>
              <el-input
                v-model="formData.name"
                placeholder="请输入项目名称"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>

            <!-- 项目封面 - 空白项目时显示在这里 -->
            <el-form-item label="项目封面" v-if="!props.templateId">
              <div class="cover-upload-single">
                <el-upload
                  ref="uploadRef"
                  class="cover-upload"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  action="#"
                  accept="image/*"
                >
                  <div class="cover-display">
                    <div v-if="projectCover" class="cover-image-wrapper">
                      <img
                        :src="projectCover"
                        alt="项目封面"
                        class="cover-image"
                      />
                      <div class="cover-overlay">
                        <span class="overlay-text">更换</span>
                      </div>
                    </div>
                    <div v-else class="cover-placeholder">
                      <el-icon class="upload-icon">
                        <Upload />
                      </el-icon>
                      <span class="upload-text">上传封面</span>
                    </div>
                  </div>
                </el-upload>
              </div>
            </el-form-item>

            <!-- 项目类型 -->
            <el-form-item label="项目类型" prop="projectTypeId" required>
              <!-- :disabled="!!props.templateId" -->
              <el-select
                v-model="formData.projectTypeId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="type in projectTypes"
                  :key="type.id"
                  :label="
                    typeof type.name === 'object'
                      ? type.name['zh_CN']
                      : type.name
                  "
                  :value="type.id"
                />
              </el-select>
            </el-form-item>

            <!-- 生命周期 -->
            <el-form-item
              label="生命周期"
              prop="lifecycle"
              required
              v-if="false"
            >
              <el-select
                v-model="formData.lifecycle"
                placeholder="根据实际标准定义的生命周期显示"
                style="width: 100%"
              >
                <el-option
                  v-for="lifecycle in lifecycles"
                  :key="lifecycle.id"
                  :label="lifecycle.name"
                  :value="lifecycle.id"
                />
              </el-select>
            </el-form-item>

            <!-- 计划日期 -->
            <el-form-item label="计划日期" class="date-range-item">
              <div class="date-range-wrapper">
                <el-form-item prop="planStartDate" class="date-item">
                  <el-date-picker
                    v-model="formData.planStartDate"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    type="daterange"
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </div>
            </el-form-item>

            <!-- 计划工期 -->
            <el-form-item label="计划工期" prop="plannedDurationDay">
              <div class="duration-display">
                <el-input-number
                  :controls="false"
                  step-strictly
                  v-model="formData.plannedDurationDay"
                  :min="1"
                  class="duration-input"
                />
                <el-select
                  v-model="formData.durationUnit"
                  class="duration-unit"
                >
                  <el-option label="天" value="天" />
                  <el-option label="月" value="月" />
                </el-select>
              </div>
            </el-form-item>

            <el-form-item label="项目描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                placeholder="请描述一下该项目"
                maxlength="300"
                show-word-limit
                :rows="3"
              />
            </el-form-item>

            <!-- 任务序号 -->
            <el-form-item
              label="任务序号"
              prop="taskNumber"
              v-if="!props.templateId"
            >
              <el-input
                v-model="formData.taskNumber"
                placeholder="请输入"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" :disabled="submitting"
          >上一步</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          新建
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, computed, watch, onUnmounted } from "vue";
  import {
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElDatePicker,
    ElButton,
    ElMessage,
    ElUpload,
    ElIcon,
    type FormInstance,
    type FormRules,
    type UploadInstance,
  } from "element-plus";
  import { Upload } from "@element-plus/icons-vue";
  import {
    getProjectTemplateDetail,
    getProjectTypes,
    getLifecycles,
    createProjectFromTemplate,
    type ProjectType,
    type Lifecycle,
  } from "@/api/template";
  import type { ProjectTemplateVO } from "@/interface/project";

  interface CreateProjectFormDialogProps {
    modelValue: boolean;
    templateId?: string; // 如果是从模板创建，传入模板ID
  }

  interface CreateProjectFormData {
    name: string;
    projectTypeId: string;
    lifecycle: string;
    planStartDate: string;
    planEndDate: string;
    description: string;
    cover?: string; // 项目封面URL
    plannedDurationDay: string;
    durationUnit: string; // 工期单位：天/月
    taskNumber?: string; // 任务序号
  }

  const props = withDefaults(defineProps<CreateProjectFormDialogProps>(), {
    modelValue: false,
    templateId: undefined,
  });

  const emit = defineEmits<{
    (e: "update:modelValue", value: boolean): void;
    (e: "submit", formData: any): void;
    (e: "cancel"): void;
  }>();

  const visible = ref(false);
  const loading = ref(false);
  const submitting = ref(false);
  const formRef = ref<FormInstance>();
  const uploadRef = ref<UploadInstance>();
  const templateDetail = ref<ProjectTemplateVO>();
  const projectCover = ref<string>(""); // 项目封面URL

  // 项目类型和生命周期数据
  const projectTypes = ref<ProjectType[]>([]);
  const lifecycles = ref<Lifecycle[]>([]);

  // 表单数据
  const formData = ref<CreateProjectFormData>({
    name: "",
    projectTypeId: "",
    lifecycle: "",
    planStartDate: "",
    planEndDate: "",
    description: "",
    cover: "",
    plannedDurationDay: "",
    durationUnit: "天", // 默认为天
    taskNumber: "", // 任务序号
  });

  // 对话框标题
  const dialogTitle = computed(() => {
    return props.templateId ? "从模板新建项目" : "创建空白项目";
  });

  // 获取模板名称
  const getTemplateName = () => {
    if (props.templateId && templateDetail.value) {
      // 从模板创建时显示模板名称
      if (typeof templateDetail.value.name === "object") {
        return (
          templateDetail.value.name?.["zh_CN"] ||
          templateDetail.value.name?.["en"] ||
          "未命名模板"
        );
      }
      return templateDetail.value.name || "未命名模板";
    } else {
      // 空白项目时显示默认名称
      return "空白项目";
    }
  };

  // 上传前验证
  const beforeUpload = (file: File) => {
    const isImage = file.type.startsWith("image/");
    const isLt5M = file.size / 1024 / 1024 < 5;

    if (!isImage) {
      ElMessage.error("只能上传图片文件!");
      return false;
    }
    if (!isLt5M) {
      ElMessage.error("图片大小不能超过 5MB!");
      return false;
    }

    // 预览图片
    const reader = new FileReader();
    reader.onload = (e) => {
      projectCover.value = e.target?.result as string;
      formData.value.cover = e.target?.result as string;
    };
    reader.readAsDataURL(file);

    // 阻止自动上传，我们只做本地预览
    return false;
  };

  // 上传成功回调
  const handleUploadSuccess = () => {
    ElMessage.success("封面上传成功");
    // 这里可以处理服务器返回的图片URL
    // projectCover.value = response.url;
    // formData.value.cover = response.url;
  };

  // 上传失败回调
  const handleUploadError = (error: any) => {
    console.error("上传失败:", error);
    ElMessage.error("封面上传失败");
  };

  // 表单验证规则
  const formRules: FormRules = {
    name: [
      { required: true, message: "请输入项目名称", trigger: "blur" },
      { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" },
    ],
    projectTypeId: [
      { required: true, message: "请选择项目类型", trigger: "change" },
    ],
    lifecycle: [
      { required: false, message: "请选择生命周期", trigger: "change" },
    ],
    planStartDate: [
      { required: false, message: "请选择开始日期", trigger: "change" },
    ],
    planEndDate: [
      { required: false, message: "请选择结束日期", trigger: "change" },
      {
        validator: (_rule, value, callback) => {
          if (value && formData.value.planStartDate) {
            const start = new Date(formData.value.planStartDate);
            const end = new Date(value);
            if (end < start) {
              callback(new Error("结束日期不能早于开始日期"));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
        trigger: "change",
      },
    ],
    plannedDurationDay: [
      { required: false, message: "请输入计划工期", trigger: "blur" },
      { type: "number", min: 1, message: "工期必须大于0", trigger: "blur" },
    ],
    description: [
      { required: false, message: "请输入项目描述", trigger: "blur" },
      { max: 300, message: "最多 300 个字符", trigger: "blur" },
    ],
  };

  // 获取项目类型列表
  const fetchProjectTypes = async () => {
    try {
      const response = await getProjectTypes({
        pageNo: 1,
        pageSize: 999,
      });
      const data = (response as any).data || response;
      projectTypes.value = data.result || [];
    } catch (error) {
      console.error("获取项目类型失败:", error);
    }
  };

  // 获取生命周期列表
  const fetchLifecycles = async () => {
    try {
      const response = await getLifecycles({
        pageNo: 1,
        pageSize: 999,
      });
      const data = (response as any).data || response;
      lifecycles.value = data.result || [];
    } catch (error) {
      console.error("获取生命周期失败:", error);
      ElMessage.error("获取生命周期失败");
    }
  };

  // 获取模板详情并填充表单
  const fetchTemplateDetail = async () => {
    if (!props.templateId) {
      // 空白项目，不需要获取模板详情，使用默认值
      console.log("创建空白项目，使用默认参数");
      return;
    }

    loading.value = true;
    try {
      console.log("从模板创建项目，获取模板详情:", props.templateId);
      const response = await getProjectTemplateDetail(props.templateId);
      const data = (response as any).data || response;
      templateDetail.value = data;

      // 用模板数据填充表单
      if (templateDetail.value) {
        // 项目名称：使用模板名称作为默认值
        formData.value.name =
          typeof templateDetail.value.name === "object"
            ? templateDetail.value.name?.["zh_CN"] || ""
            : templateDetail.value.name || "";

        // 项目描述：使用模板描述
        formData.value.description = templateDetail.value.remark || "";

        // 项目类型：使用模板的软件类型（从模板创建时不可修改）
        // if (templateDetail.value.software) {
        formData.value.projectTypeId = templateDetail.value.projectType?.id;
        // }

        // 项目封面：使用模板封面（从模板创建时自动使用模板封面）
        if (templateDetail.value.cover) {
          projectCover.value = templateDetail.value.cover;
          formData.value.cover = templateDetail.value.cover;
        }

        console.log("模板数据已填充到表单:", formData.value);
        console.log(
          "项目类型已设置为模板类型（不可修改）:",
          templateDetail.value.software,
        );
        console.log("项目封面已设置为模板封面:", templateDetail.value.cover);
      }
    } catch (error) {
      console.error("获取模板详情失败:", error);
      ElMessage.error("获取模板详情失败");
    } finally {
      loading.value = false;
    }
  };

  // 关闭对话框
  const handleClose = () => {
    visible.value = false;
    handleBodyScroll(false);
    emit("cancel");
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return;

    try {
      await formRef.value.validate();
      submitting.value = true;
      loading.value = true; // 显示整体加载遮罩

      const [plannedStartTime, plannedEndTime] = formData.value.planStartDate;
      debugger;
      const _plannedStartTime = plannedStartTime
        ? `${plannedStartTime} 00:00:00`
        : undefined;
      const _plannedEndTime = plannedEndTime
        ? `${plannedEndTime} 23:59:59`
        : undefined;
      // 准备提交数据
      const submitData = {
        name: {
          zh_CN: formData.value.name,
        },
        projectTypeId: formData.value.projectTypeId,
        plannedStartTime: _plannedStartTime,
        plannedEndTime: _plannedEndTime,
        remark: formData.value.description,
        cover: formData.value.cover,
        plannedDurationDay: formData.value.plannedDurationDay,
        durationUnit: formData.value.durationUnit,
        taskNumber: formData.value.taskNumber, // 添加任务序号
      };

      // 根据是否有模板ID决定调用哪个接口
      // 从模板创建项目
      await createProjectFromTemplate(submitData);
      ElMessage.success(`从模板创建项目成功: ${formData.value.name}`);

      // 成功后关闭对话框
      handleClose();
      resetForm();

      // 通知父组件项目创建成功
      emit("submit", submitData);
    } catch (error) {
      console.error("创建项目失败:", error);
      ElMessage.error("创建项目失败，请重试");
    } finally {
      submitting.value = false;
      loading.value = false; // 隐藏整体加载遮罩
    }
  };

  // 重置表单
  const resetForm = () => {
    formData.value = {
      name: "",
      projectTypeId: "",
      lifecycle: "",
      planStartDate: "",
      planEndDate: "",
      description: "",
      cover: "",
      plannedDurationDay: "",
      durationUnit: "天", // 默认为天
      taskNumber: "", // 任务序号
    };
    projectCover.value = "";
    formRef.value?.clearValidate();
  };

  // 控制 body 滚动
  const handleBodyScroll = (lock: boolean) => {
    if (lock) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "";
    }
  };

  // 监听 modelValue 变化
  watch(
    () => props.modelValue,
    (newValue) => {
      console.log("CreateProjectFormDialog: modelValue 变化:", newValue);
      console.log("templateId:", props.templateId);
      visible.value = newValue;
      handleBodyScroll(newValue);

      // 弹窗打开时获取数据
      if (newValue) {
        resetForm();
        // 获取项目类型和生命周期数据
        fetchProjectTypes();
        fetchLifecycles();

        // 根据是否有templateId决定处理方式
        if (props.templateId) {
          console.log("从模板创建项目，templateId:", props.templateId);
          fetchTemplateDetail(); // 获取模板详情并填充表单
        } else {
          console.log("创建空白项目，使用默认参数");
          // 空白项目不需要额外处理，使用默认的空表单
        }
      }
    },
  );

  // 监听 visible 变化
  watch(visible, (newValue) => {
    emit("update:modelValue", newValue);
    handleBodyScroll(newValue);
  });

  // 组件卸载时恢复body滚动
  onUnmounted(() => {
    handleBodyScroll(false);
  });

  // 暴露方法供父组件调用
  defineExpose({
    open: () => {
      visible.value = true;
      handleBodyScroll(true);
      resetForm();
      // 获取项目类型和生命周期数据
      fetchProjectTypes();
      fetchLifecycles();

      // 根据是否有templateId决定处理方式
      if (props.templateId) {
        console.log("从模板创建项目，templateId:", props.templateId);
        fetchTemplateDetail(); // 获取模板详情并填充表单
      } else {
        console.log("创建空白项目，使用默认参数");
        // 空白项目不需要额外处理，使用默认的空表单
      }
    },
    close: () => {
      visible.value = false;
      handleBodyScroll(false);
    },
  });
</script>

<style scoped lang="scss">
  .create-project-form-dialog {
    // max-height: 80vh;
    // padding: 24px;

    :deep(.el-dialog__header) {
      border-bottom: 10px;
      .el-dialog__title {
        font-size: 16px;
        font-weight: 500;
        color: #1d2129;
      }
    }

    .dialog-content-wrapper {
      max-height: 70vh;
      overflow-y: auto;
      overflow-x: hidden;

      // 隐藏滚动条但保持滚动功能
      scrollbar-width: none; // Firefox
      -ms-overflow-style: none; // IE 10+

      &::-webkit-scrollbar {
        display: none; // Chrome, Safari, Opera
      }
    }

    .dialog-content {
      display: flex;
      gap: 24px;

      &:has(.full-width) {
        justify-content: center;
      }
    }

    .left-preview {
      flex-shrink: 0;
      width: 280px;

      .preview-image {
        width: 100%;
        height: 180px;
        border-radius: 8px;
        overflow: hidden;
        background: #f5f6f7;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        justify-content: center;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .blank-project-preview {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

          .blank-icon {
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
      }

      .template-info {
        margin-bottom: 36px;

        .template-name {
          font-size: 14px;
          font-weight: 500;
          color: #1d2129;
          margin: 0 0 8px 0;
          line-height: 20px;
        }

        .template-description {
          font-size: 13px;
          color: #86909c;
          line-height: 20px;
          margin: 0;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      }

      .change-cover-section {
        .section-label {
          font-size: 14px;
          font-weight: 500;
          color: #1d2129;
          margin-bottom: 8px;
        }

        .template-cover-info {
          margin-bottom: 8px;

          .cover-source-text {
            font-size: 12px;
            color: #86909c;
            background: #f2f3f5;
            padding: 2px 8px;
            border-radius: 4px;
          }
        }

        .cover-upload {
          width: 100%;

          .change-cover-btn {
            width: 100%;
            height: 36px;
            border: 1px dashed #c9cdd4;
            border-radius: 4px;
            background: #fff;
            color: #4e5969;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;

            &:hover {
              border-color: #1aa1fb;
              color: #1aa1fb;
              background: rgba(20, 86, 240, 0.05);
            }
          }
        }
      }
    }

    // 空白项目封面上传样式
    .cover-upload-single {
      .cover-upload {
        .cover-display {
          border: 1px dashed #d9d9d9;
          width: 66px;
          height: 66px;
          border-radius: 8px;
          overflow: hidden;
          cursor: pointer;
          transition: all 0.3s ease;

          .cover-image-wrapper {
            position: relative;
            width: 100%;
            height: 100%;

            .cover-image {
              width: 100%;
              height: 100%;
              object-fit: cover;
              display: block;
            }

            .cover-overlay {
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              background: rgba(0, 0, 0, 0.5);
              display: flex;
              align-items: center;
              justify-content: center;
              opacity: 0;
              transition: opacity 0.3s ease;

              .overlay-text {
                color: white;
                font-size: 16px;
                font-weight: 500;
              }
            }

            &:hover .cover-overlay {
              opacity: 1;
            }
          }

          .cover-placeholder {
            width: 100%;
            height: 100%;
            // border: 2px dashed #d9d9d9;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: #fafafa;
            transition: all 0.3s ease;

            .upload-icon {
              font-size: 24px;
              color: #8c8c8c;
              margin-bottom: 8px;
            }

            .upload-text {
              color: #8c8c8c;
              font-size: 14px;
            }

            &:hover {
              border-color: #1aa1fb;
              background: rgba(20, 86, 240, 0.05);

              .upload-icon,
              .upload-text {
                color: #1aa1fb;
              }
            }
          }
        }
      }
    }

    .right-form {
      flex: 1;
      min-width: 0;

      &.full-width {
        max-width: 600px;
        margin: 0 auto;
      }
    }
  }

  .duration-display {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
    color: #4e5969;
    font-size: 14px;

    .duration-input {
      flex: 1;

      .el-input__inner {
        text-align: center;
        background-color: #f7f8fa;
        border-color: #e5e6eb;
      }
    }

    .duration-unit {
      width: 120px;
      flex-shrink: 0;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;

    .el-button {
      padding: 8px 20px;
      font-size: 14px;
    }
  }

  :deep(.date-range-wrapper) {
    width: 100%;
  }
</style>

<style lang="scss">
  .create-project-form-dialog {
    // padding: 0;
    margin-top: 10vh !important;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    max-height: 80vh;

    .el-dialog__header {
      padding-bottom: 10px;
      padding-top: 0;
      flex-shrink: 0;
    }

    .el-dialog__body {
      overflow: hidden !important;
      flex: 1;
      display: flex;
      flex-direction: column;
    }

    .el-dialog__footer {
      padding-top: 6px;
      padding-bottom: 0;
      flex-shrink: 0;
    }
  }
</style>
